#include "exportuistatesynchronizer.h"
#include <QDebug>
#include <QPropertyAnimation>
#include <QEasingCurve>
#include <QTimer>

ExportUIStateSynchronizer::ExportUIStateSynchronizer(UnifiedExportStateManager* stateManager, 
                                                   QPushButton* exportButton,
                                                   QProgressBar* progressBar,
                                                   QLabel* statusLabel,
                                                   QObject* parent)
    : QObject(parent)
    , m_stateManager(stateManager)
    , m_exportButton(exportButton)
    , m_progressBar(progressBar)
    , m_statusLabel(statusLabel)
    , m_buttonAnimation(nullptr)
    , m_progressAnimation(nullptr)
    , m_statusAnimation(nullptr)
    , m_completionTimer(nullptr)
{
    // 创建动画对象
    m_buttonAnimation = new QPropertyAnimation(this);
    m_progressAnimation = new QPropertyAnimation(this);
    m_statusAnimation = new QPropertyAnimation(this);
    m_completionTimer = new QTimer(this);
    
    // 设置动画属性
    m_buttonAnimation->setTargetObject(m_exportButton);
    m_buttonAnimation->setPropertyName("styleSheet");
    m_buttonAnimation->setDuration(300);
    m_buttonAnimation->setEasingCurve(QEasingCurve::OutCubic);
    
    m_progressAnimation->setTargetObject(m_progressBar);
    m_progressAnimation->setPropertyName("value");
    m_progressAnimation->setDuration(200);
    m_progressAnimation->setEasingCurve(QEasingCurve::OutQuad);
    
    m_statusAnimation->setTargetObject(m_statusLabel);
    m_statusAnimation->setPropertyName("styleSheet");
    m_statusAnimation->setDuration(250);
    m_statusAnimation->setEasingCurve(QEasingCurve::OutCubic);
    
    // 设置完成定时器
    m_completionTimer->setSingleShot(true);
    m_completionTimer->setInterval(m_completionDelayMs);
    
    // 连接信号
    connect(m_stateManager, &UnifiedExportStateManager::stateChanged,
            this, &ExportUIStateSynchronizer::onStateChanged);
    connect(m_stateManager, &UnifiedExportStateManager::fileStateChanged,
            this, &ExportUIStateSynchronizer::onFileStateChanged);
    connect(m_stateManager, &UnifiedExportStateManager::contextChanged,
            this, &ExportUIStateSynchronizer::onContextChanged);
    connect(m_stateManager, &UnifiedExportStateManager::exportProgressChanged,
            this, &ExportUIStateSynchronizer::onProgressChanged);
    
    // 连接动画完成信号
    connect(m_buttonAnimation, &QPropertyAnimation::finished,
            this, &ExportUIStateSynchronizer::onExportingAnimationFinished);
    connect(m_completionTimer, &QTimer::timeout,
            this, &ExportUIStateSynchronizer::onCompletionAnimationFinished);
    
    // 初始化UI状态
    updateExportButton();
    updateProgressBar();
    updateStatusLabel();
    updateTooltips();
    
}

void ExportUIStateSynchronizer::setAnimationEnabled(bool enabled)
{
    m_animationEnabled = enabled;
    if (!enabled) {
        stopAllAnimations();
    }
}

void ExportUIStateSynchronizer::setTooltipEnabled(bool enabled)
{
    m_tooltipEnabled = enabled;
    updateTooltips();
}

void ExportUIStateSynchronizer::setCompletionDelay(int delayMs)
{
    m_completionDelayMs = delayMs;
    m_completionTimer->setInterval(delayMs);
}

void ExportUIStateSynchronizer::onStateChanged(UnifiedExportStateManager::ExportState newState, 
                                              UnifiedExportStateManager::ExportState oldState)
{
    m_currentState = newState;
    
    
    // 更新UI组件
    updateExportButton();
    updateProgressBar();
    updateStatusLabel();
    updateTooltips();
    
    // 启动相应的动画
    if (m_animationEnabled) {
        switch (newState) {
            case UnifiedExportStateManager::ExportState::Exporting:
                startExportingAnimation();
                break;
            case UnifiedExportStateManager::ExportState::Completed:
                startCompletionAnimation();
                break;
            case UnifiedExportStateManager::ExportState::Failed:
                startErrorAnimation();
                break;
            default:
                stopAllAnimations();
                break;
        }
    }
}

void ExportUIStateSynchronizer::onFileStateChanged(UnifiedExportStateManager::FileState newState)
{
    m_currentFileState = newState;
    
    
    // 更新按钮状态
    updateExportButton();
    updateTooltips();
}

void ExportUIStateSynchronizer::onContextChanged(const UnifiedExportStateManager::ExportContext& context)
{
    m_currentContext = context;
    
    // 更新进度条
    updateProgressBar();
    updateStatusLabel();
}

void ExportUIStateSynchronizer::onProgressChanged(int completed, int total, const QString& status)
{
    if (m_progressBar) {
        m_progressBar->setMaximum(total);
        m_progressBar->setValue(completed);
        
        if (m_animationEnabled && m_progressAnimation) {
            m_progressAnimation->setStartValue(m_progressBar->value());
            m_progressAnimation->setEndValue(completed);
            m_progressAnimation->start();
        }
    }
    
    if (m_statusLabel) {
        m_statusLabel->setText(status);
    }
    
    updateTooltips();
}

void ExportUIStateSynchronizer::updateExportButton()
{
    if (!m_exportButton) return;
    
    QString buttonText;
    bool buttonEnabled = false;
    QString buttonStyle = getButtonStyle(m_currentState);
    
    switch (m_currentState) {
        case UnifiedExportStateManager::ExportState::Idle:
            buttonText = "一键导出";
            buttonEnabled = (m_currentFileState == UnifiedExportStateManager::FileState::HasFiles);
            break;
        case UnifiedExportStateManager::ExportState::Ready:
            buttonText = "一键导出";
            buttonEnabled = true;
            break;
        case UnifiedExportStateManager::ExportState::Exporting:
            buttonText = "取消导出";
            buttonEnabled = true;
            break;
        case UnifiedExportStateManager::ExportState::Completed:
            buttonText = "一键导出";
            buttonEnabled = true;
            break;
        case UnifiedExportStateManager::ExportState::Failed:
            buttonText = "重试导出";
            buttonEnabled = true;
            break;
        case UnifiedExportStateManager::ExportState::Cancelled:
            buttonText = "一键导出";
            buttonEnabled = true;
            break;
    }
    
    m_exportButton->setText(buttonText);
    m_exportButton->setEnabled(buttonEnabled);
    m_exportButton->setStyleSheet(buttonStyle);
}

void ExportUIStateSynchronizer::updateProgressBar()
{
    if (!m_progressBar) return;
    
    bool shouldShow = (m_currentState == UnifiedExportStateManager::ExportState::Exporting ||
                      m_currentState == UnifiedExportStateManager::ExportState::Completed);
    
    m_progressBar->setVisible(shouldShow);
    
    if (shouldShow) {
        m_progressBar->setMaximum(m_currentContext.totalFiles);
        m_progressBar->setValue(m_currentContext.completedFiles);
        m_progressBar->setStyleSheet(getProgressBarStyle());
    }
}

void ExportUIStateSynchronizer::updateStatusLabel()
{
    if (!m_statusLabel) return;
    
    bool shouldShow = (m_currentState != UnifiedExportStateManager::ExportState::Idle &&
                      m_currentState != UnifiedExportStateManager::ExportState::Ready);
    
    m_statusLabel->setVisible(shouldShow);
    
    if (shouldShow) {
        m_statusLabel->setText(m_currentContext.currentStatus);
        m_statusLabel->setStyleSheet(getStatusLabelStyle());
    }
}

void ExportUIStateSynchronizer::updateTooltips()
{
    if (!m_tooltipEnabled) return;
    
    if (m_exportButton) {
        m_exportButton->setToolTip(getButtonTooltip(m_currentState));
    }
    
    if (m_progressBar && m_progressBar->isVisible()) {
        m_progressBar->setToolTip(getProgressTooltip(m_currentContext.completedFiles, 
                                                    m_currentContext.totalFiles));
    }
    
    if (m_statusLabel && m_statusLabel->isVisible()) {
        m_statusLabel->setToolTip(getStatusTooltip(m_currentContext.currentStatus));
    }
}

void ExportUIStateSynchronizer::startExportingAnimation()
{
    if (!m_animationEnabled) return;
    
    // 按钮呼吸动画
    if (m_buttonAnimation) {
        QString normalStyle = getButtonStyle(UnifiedExportStateManager::ExportState::Exporting);
        QString pulseStyle = normalStyle.replace("#FF3B30", "#FF6B60");
        
        m_buttonAnimation->setStartValue(normalStyle);
        m_buttonAnimation->setEndValue(pulseStyle);
        m_buttonAnimation->setLoopCount(-1); // 无限循环
        m_buttonAnimation->start();
    }
}

void ExportUIStateSynchronizer::startCompletionAnimation()
{
    if (!m_animationEnabled) return;
    
    // 停止其他动画
    stopAllAnimations();
    
    // 启动完成定时器
    m_completionTimer->start();
}

void ExportUIStateSynchronizer::startErrorAnimation()
{
    if (!m_animationEnabled) return;
    
    // 错误闪烁动画
    if (m_buttonAnimation) {
        QString normalStyle = getButtonStyle(UnifiedExportStateManager::ExportState::Failed);
        QString errorStyle = normalStyle.replace("#FF3B30", "#FF0000");
        
        m_buttonAnimation->setStartValue(normalStyle);
        m_buttonAnimation->setEndValue(errorStyle);
        m_buttonAnimation->setLoopCount(3); // 闪烁3次
        m_buttonAnimation->start();
    }
}

void ExportUIStateSynchronizer::stopAllAnimations()
{
    if (m_buttonAnimation) {
        m_buttonAnimation->stop();
    }
    if (m_progressAnimation) {
        m_progressAnimation->stop();
    }
    if (m_statusAnimation) {
        m_statusAnimation->stop();
    }
    if (m_completionTimer) {
        m_completionTimer->stop();
    }
}

QString ExportUIStateSynchronizer::getButtonStyle(UnifiedExportStateManager::ExportState state) const
{
    switch (state) {
        case UnifiedExportStateManager::ExportState::Exporting:
            return "QPushButton { "
                   "    background-color: #FF3B30; "  // 红色背景表示取消操作
                   "    color: white; "
                   "    border: none; "
                   "    border-radius: 2px; "
                   "    padding: 2px 8px; "
                   "    font-weight: 500; "
                   "    font-size: 12px; "
                   "} "
                   "QPushButton:hover { "
                   "    background-color: #D70015; "  // 悬停时更深的红色
                   "    transform: translateY(-1px); "
                   "} "
                   "QPushButton:pressed { "
                   "    background-color: #B71C1C; "  // 按下时最深的红色
                   "    transform: translateY(0px); "
                   "}";
                   
        case UnifiedExportStateManager::ExportState::Failed:
            return "QPushButton { "
                   "    background-color: #FF9500; "  // 橙色背景表示重试
                   "    color: white; "
                   "    border: none; "
                   "    border-radius: 2px; "
                   "    padding: 2px 8px; "
                   "    font-weight: 500; "
                   "    font-size: 12px; "
                   "} "
                   "QPushButton:hover { "
                   "    background-color: #E6850E; "
                   "    transform: translateY(-1px); "
                   "} "
                   "QPushButton:pressed { "
                   "    background-color: #CC7700; "
                   "    transform: translateY(0px); "
                   "}";
                   
        default:
            return "QPushButton { "
                   "    background-color: #4A4A4A; "  // 深灰色
                   "    color: white; "
                   "    border: none; "
                   "    border-radius: 2px; "
                   "    padding: 2px 8px; "
                   "    font-weight: 500; "
                   "    font-size: 12px; "
                   "} "
                   "QPushButton:hover { "
                   "    background-color: #3A3A3A; "  // 悬停时更深的灰色
                   "    transform: translateY(-1px); "
                   "} "
                   "QPushButton:pressed { "
                   "    background-color: #2A2A2A; "  // 按下时最深的灰色
                   "    transform: translateY(0px); "
                   "} "
                   "QPushButton:disabled { "
                   "    background-color: #8E8E93; "  // Apple Gray
                   "    color: #C7C7CC; "
                   "    transform: none; "
                   "}";
    }
}

QString ExportUIStateSynchronizer::getProgressBarStyle() const
{
    return "QProgressBar { "
           "    border: 1px solid #D1D1D6; "  // Apple Light Gray
           "    border-radius: 8px; "  // 更现代的圆角
           "    text-align: center; "
           "    background-color: #F2F2F7; "  // Apple Background Gray
           "    color: #1D1D1F; "  // Apple Label
           "    font-size: 11px; "
           "    font-weight: 500; "
           "} "
           "QProgressBar::chunk { "
           "    background: qlineargradient(x1:0, y1:0, x2:1, y2:0, "
           "        stop:0 #007AFF, stop:1 #34C759); "  // Apple Blue to Green gradient
           "    border-radius: 7px; "
           "}";
}

QString ExportUIStateSynchronizer::getStatusLabelStyle() const
{
    return "QLabel { "
           "    color: #1D1D1F; "  // Apple Label
           "    font-size: 12px; "
           "    font-weight: 400; "
           "    padding: 2px 6px; "
           "    background-color: rgba(0, 122, 255, 0.1); "  // 淡蓝色背景
           "    border-radius: 4px; "
           "}";
}

QString ExportUIStateSynchronizer::getButtonTooltip(UnifiedExportStateManager::ExportState state) const
{
    switch (state) {
        case UnifiedExportStateManager::ExportState::Idle:
            return "请先添加要导出的文件";
        case UnifiedExportStateManager::ExportState::Ready:
            return "点击开始导出所有文件";
        case UnifiedExportStateManager::ExportState::Exporting:
            return "点击取消当前导出操作";
        case UnifiedExportStateManager::ExportState::Completed:
            return "导出完成，点击可重新导出";
        case UnifiedExportStateManager::ExportState::Failed:
            return "导出失败，点击重试";
        case UnifiedExportStateManager::ExportState::Cancelled:
            return "导出已取消，点击重新开始";
        default:
            return "";
    }
}

QString ExportUIStateSynchronizer::getProgressTooltip(int completed, int total) const
{
    return QString("导出进度: %1/%2 (%3%)")
           .arg(completed)
           .arg(total)
           .arg(total > 0 ? QString::number((double)completed / total * 100, 'f', 1) : "0");
}

QString ExportUIStateSynchronizer::getStatusTooltip(const QString& status) const
{
    return QString("状态: %1").arg(status);
}

void ExportUIStateSynchronizer::onExportingAnimationFinished()
{
    // 导出动画完成处理
}

void ExportUIStateSynchronizer::onCompletionAnimationFinished()
{
    // 完成动画处理
}

void ExportUIStateSynchronizer::onErrorAnimationFinished()
{
    // 错误动画完成处理
}
